<?php
include_once( "common.php" );
checkLogin( STATUS_USER );

# Check values
if ( ! isValidEntry( "Project", $_POST["project"] ) or ! isValidEntry( "User", $_POST["assigned"] ) or ! isValidEntry( "Priority", $_POST["priority"] ) or ! isValidEntry( "Status", $_POST["status"] ) or ! isValidEntry( "Bug", $_POST["id"] ) )
    outputAlert( "Invalid input", "You entered invalid input." );

# Make sure the user can update this bug
if ( ! canSeeBug( $_POST["id"] ) )
    outputAlert( "Insufficient rights", "You do not have sufficient rights to update this bug." );

# Make sure the assigned user has visibility for this project
$result = db_query( "SELECT * FROM UserProject WHERE UserProject.user = {$_POST["assigned"]} AND UserProject.project = {$_POST["project"]}" );
if ( $_POST["assigned"] != 0 and db_num_rows( $result ) != 1 )
    outputAlert( "Invalid user", "The assigned user does not have visibility for this project." );
if ( ! hasStatus( STATUS_USER, $_POST["assigned"] ) )
    outputAlert( "Invalid user", "The assigned user does not have sufficient privileges to be assigned to this project." );

# Clean up the comment
$_POST["comment"] = str_replace( "\r", "", $_POST["comment"] );
$_POST["comment"] = str_replace( "\n", "", $_POST["comment"] );
$_POST["comment"] = trim( $_POST["comment"] );

# Get the bug's old information
$result = db_query( "SELECT * FROM Bug WHERE Bug.id = {$_POST["id"]}" );
$row = db_fetch_object( $result );

# Record changes
$changes = array();
if ( $_POST["project"] != $row->project )
    $changes["project"] = $_POST["project"];
if ( $_POST["assigned"] != $row->assigned )
    $changes["assigned"] = $_POST["assigned"];
if ( $_POST["priority"] != $row->priority )
    $changes["priority"] = $_POST["priority"];
if ( $_POST["status"] != $row->status )
    $changes["status"] = $_POST["status"];

# Update the bug if there were changes
if ( count( $changes ) > 0 or $_POST["comment"] != "" )
{
    db_query( "UPDATE Bug SET Bug.assigned = {$_POST["assigned"]}, Bug.priority = {$_POST["priority"]}, Bug.status = {$_POST["status"]}, Bug.project = {$_POST["project"]} WHERE Bug.id = {$_POST["id"]}" ) or outputAlert( "Database error", "There was a database error and the bug was not updated." );

    # Log it
    addLog( $_POST["id"], $_POST["comment"], $changes, $_SESSION["user"] ) or outputAlert( "Database error", "There was a database error and the changes were not logged." );
}

# Route to the main page if the bug was closed
if ( getNameByID( "Status", $_POST["status"] ) == "Closed" )
    header( "Location: main.php" );
else
    header( "Location: viewBug.php?id={$_POST["id"]}" );
?>
